package com.example;

import com.example.uploadminio.ui.MainFrame;
import com.example.uploadminio.service.MinioUploader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javax.swing.*;
import java.awt.*;
import java.nio.file.Files;
import java.nio.file.Path;

@SpringBootApplication(scanBasePackages = "com.example")
public class Main {

    public static void main(String[] args) {
        System.setProperty("java.awt.headless", "false");

        // 全局异常处理：控制台打印 + 弹窗提示 + 写入 error.log
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> handleException("未捕获异常", e));

        ConfigurableApplicationContext context = null;
        try {
            // 启动 Spring Boot
            context = SpringApplication.run(Main.class, args);

            // 检查无头模式
            if (!GraphicsEnvironment.isHeadless()) {
                // Mac 系统特殊设置
                if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                    System.setProperty("apple.laf.useScreenMenuBar", "true");
                    System.setProperty("apple.awt.application.name", "MinIO文件上传工具");
                }

                // 设置系统外观
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ignored) {}

                // 启动 GUI
                SwingUtilities.invokeLater(() -> {
                    try {
                        MainFrame frame = new MainFrame();
                        frame.setVisible(true);
                        System.out.println("GUI界面已启动");
                    } catch (Exception e) {
                        handleException("启动主窗口失败", e);
                    }
                });
            } else {
                System.out.println("运行在无头模式，跳过 GUI 启动");
            }

        } catch (Exception e) {
            handleException("程序启动失败", e);
        }
    }

    /**
     * 异常处理统一方法：控制台 + 弹窗 + 写 error.log
     */
    private static void handleException(String msg, Throwable e) {
        // 控制台打印
        System.err.println(msg + ": " + e);
        e.printStackTrace();

        // 弹窗提示
        try {
            JOptionPane.showMessageDialog(null,
                    msg + "，请查看 error.log\n" + e.toString(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ignored) {}

        // 写入 error.log
        try {
            Path logPath = Path.of("error.log");
            StringBuilder logContent = new StringBuilder(msg + System.lineSeparator());
            logContent.append(e.toString()).append(System.lineSeparator());
            for (StackTraceElement el : e.getStackTrace()) {
                logContent.append("\tat ").append(el).append(System.lineSeparator());
            }
            Files.writeString(logPath, logContent.toString(),
                    Files.exists(logPath) ? java.nio.file.StandardOpenOption.APPEND : java.nio.file.StandardOpenOption.CREATE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
